package com.example.androidmsg.Utils;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

public class Myalarm {
    public static final String TAG = "Myalarm";

    private static final String AM_ACTION = "iflab.test.AM_ACTION"; // ACTION常量
    public void setAlarm(Context context, long triggerAtMillis) {
        triggerAtMillis=System.currentTimeMillis()+triggerAtMillis;

        // 获取AlarmManager的实例
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        // 指定闹钟的行为（在指定时间通过PendingIntent触发）
        Intent intent = new Intent(context, AlarmReceiver.class);
        intent.setAction(AM_ACTION); // 设置Action
        intent.putExtra("message","test");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        // 设置闹钟
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Log.d(TAG, "test1");
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Log.d(TAG, "test2");
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
        } else {
            Log.d(TAG, "test3");
            alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
        }
    }
}
